<template>
	<div class="table-box">
		<proTable
			ref="proTableRef"
			:columns="columns"
			:toolButton="true"
			:requestApi="registarationApi.GetRegistrationInfoListApi"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<template #tableHeader="scope">
				<el-button @click="handleModel" :icon="CirclePlus" type="primary">添加报名</el-button>
				<el-button plain type="primary" :icon="Files" @click="batchOperation(scope.selectedListIds)">批量审核</el-button>
				<el-button plain type="primary" @click="DowloadExcelClick" :icon="Download">导出报名数据</el-button>
			</template>
			<template #operation="scope">
				<el-space wrap>
					<el-tag v-if="scope.row.registrationStatus == '待审核'" style="cursor: pointer" @click="handleAudit(scope.row.id)">
						审核
					</el-tag>
					<span v-else>--</span>
				</el-space>
			</template>
			<template #auditTime="scope">
				{{ scope.row.auditTime ? dateFormat(scope.row.auditTime, undefined) : "" }}
			</template>
			<template #registrationSubmissionTime="scope">
				{{ dateFormat(scope.row.registrationSubmissionTime, undefined) }}
			</template>
		</proTable>
		<!-- 模态框 -->
		<el-dialog @closed="handleCancelClick(ruleFormRef)" v-model="centerDialogVisible" width="40%">
			<template #header>
				<p>添加报名</p>
			</template>
			<!-- 报名表单 -->
			<el-form ref="ruleFormRef" label-width="150px" :model="addRegFrom" :rules="employeeInfosForm">
				<div class="herder_item">
					<el-form-item label="参加赛事：" prop="CompetitionId">
						<el-select @change="handleCompetitionChange" v-model="addRegFrom.CompetitionId" placeholder="请选择">
							<el-option
								v-for="(item, index) in queryList.competitionList"
								:key="index"
								:label="item.lable"
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
					<el-form-item label="比赛项目：" prop="CompetitionProjectId">
						<el-select v-model="addRegFrom.CompetitionProjectId" placeholder="请选择" @change="handleProjectTypeChange">
							<el-option v-for="item in queryList.projectList" :key="item.value" :label="item.lable" :value="item.value" />
						</el-select>
					</el-form-item>
				</div>
				<div v-for="(item, index) in addRegFrom.EmployeeInfos" v-show="employeeInfosShow" :key="index" class="person_item">
					<el-form-item
						v-if="gameType == 1"
						:prop="`EmployeeInfos.${index}.CompeteTeamName`"
						label="参赛队名："
						:rules="{
							required: true,
							message: '请输入参赛队名!',
							trigger: 'blur'
						}"
					>
						<el-input v-model="item.CompeteTeamName" placeholder="请输入" />
					</el-form-item>
					<el-form-item
						label="参赛人姓名："
						:prop="`EmployeeInfos.${index}.CompeteName`"
						:rules="{ required: true, message: '请输入姓名!', trigger: 'blur' }"
					>
						<el-input v-model="item.CompeteName" placeholder="请输入" />
					</el-form-item>
					<el-form-item
						label="参赛人联系电话："
						:prop="`EmployeeInfos.${index}.CompeteTel`"
						:rules="[
							{
								required: false,
								message: '请输入参赛人联系电话！',
								trigger: 'blur'
							},
							{
								pattern: /^(13[0-9]|14[1|4|5|6|7|8|9]|15[0|1|2|3|5|6|7|8|9]|17[2|3|5|6|7|8]|18[0-9]|19[1|8|9])\d{8}$/,
								message: '手机号格式不正确',
								trigger: 'blur'
							}
						]"
					>
						<el-input @blur="handleIsTeamShowBlur(index)" v-model="item.CompeteTel" placeholder="请输入" />
					</el-form-item>
					<el-form-item
						label="参赛人身份证号："
						:prop="`EmployeeInfos.${index}.CompeteIdNo`"
						:rules="[
							{
								required: false,
								message: '请输入参赛人员身份证号！',
								trigger: 'blur'
							},
							{
								pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X)$)/,
								message: '证件号码格式有误！',
								trigger: 'blur'
							}
						]"
					>
						<el-input @blur="handleIsTeamShowBlur(index)" v-model="item.CompeteIdNo" placeholder="请输入" />
					</el-form-item>
					<!-- <el-form-item v-if="item.isTeamShow" label="* 所属团队：">
						<el-select
							v-model="item.TeamId"
							:disabled="item.isChecked"
							@visible-change="handleVisibleChange(item.CompeteName, item.CompeteIdNo, index)"
							placeholder="请选择"
						>
							<el-option v-for="i in item.teamList" :key="i.id" :label="i.teamName" :value="i.id" :disabled="i.disabled" />
						</el-select>
						<el-checkbox
							style="margin-left: 20px"
							v-model="item.isChecked"
							@change="handleIsCheckedChange(index)"
							label="无团队"
						/>
					</el-form-item> -->
					<el-form-item
						label="参赛感应器："
						:prop="`EmployeeInfos.${index}.SensorNumber`"
						:rules="[
							{
								required: true,
								message: '请输入参赛的感应器！',
								trigger: 'blur'
							},
							{
								pattern: /^[0-9,]+$/,
								message: '感应号仅限输入数字和英文状态下的(,)',
								trigger: 'blur'
							}
						]"
					>
						<el-input v-model="item.SensorNumber" placeholder="请输入，多个感应器请用逗号隔开" />
					</el-form-item>
					<div v-if="!!addRegFrom.officialOrBusiness">
						<el-form-item label="船型：">
							<el-input v-model="item.shipType" placeholder="请输入" />
						</el-form-item>
						<el-form-item label="电机品牌/型号：">
							<el-input v-model="item.electricalType" placeholder="请输入" />
						</el-form-item>
						<el-form-item label="电调品牌/型号：">
							<el-input v-model="item.electricBrand" placeholder="请输入" />
						</el-form-item>
						<el-form-item label="电池品牌：">
							<el-input v-model="item.batteryType" placeholder="请输入" />
						</el-form-item>
						<el-form-item label="遥控品牌：">
							<el-input v-model="item.remoteControl" placeholder="请输入" />
						</el-form-item>
					</div>

					<div class="person_item_btn">
						<el-button v-if="index == addRegFrom.EmployeeInfos.length - 1" @click="NewPersonClick" size="small" type="primary"
							>新增</el-button
						>
						<el-button @click="DeletePersonClick(index)" size="small" type="danger">删除</el-button>
					</div>
				</div>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleCancelClick(ruleFormRef)">取消</el-button>
					<el-button type="primary" @click="handleSubmitClick(ruleFormRef)"> 提交 </el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 审核模态框 -->
		<el-dialog @close="auditCenleClick" v-model="AuditModel" width="50%">
			<el-descriptions label-align="right" size="small">
				<template #title>
					<h3 style="padding: 0; margin: 0">报名审核</h3>
					<h6 style="padding: 0; margin: 0; margin-top: 15px">{{ AuditForm?.competitionName }}</h6>
				</template>
				<el-descriptions-item label="姓名：">{{ AuditForm?.competeName }}</el-descriptions-item>
				<el-descriptions-item label="身份证号：">{{ AuditForm?.competeIdNo }}</el-descriptions-item>
				<el-descriptions-item label="比赛项目：">{{ AuditForm?.competitionProjectName }}</el-descriptions-item>
				<el-descriptions-item label="比赛时间:">
					{{ AuditForm?.projectDateTImeStr }}
				</el-descriptions-item>
				<el-descriptions-item label="比赛报名限制最多人数："
					>{{ AuditForm?.maxEmployeeNum ? AuditForm?.maxEmployeeNum : "无限制" }}人{{
						AuditForm?.maxEmployeeNum ? "" : "数"
					}}</el-descriptions-item
				>
				<el-descriptions-item label="剩余参赛席位：">{{
					AuditForm?.remainingSeats > 0 ? AuditForm?.remainingSeats : "无限制"
				}}</el-descriptions-item>
				<el-descriptions-item label="报名序号：">{{ AuditForm?.registrationNo }}</el-descriptions-item>
			</el-descriptions>
			<div class="menberInfo">
				<div class="radioBox">
					<div class="radioText"><span>*</span>报名审核</div>
					<el-radio-group v-model="auditFrom.registrationStatus">
						<el-radio :label="1">授予比赛资格</el-radio>
						<el-radio :label="0">不授予比赛资格</el-radio>
					</el-radio-group>
				</div>
				<div class="text">
					<span>审核备注：</span>
					<el-input v-model="auditFrom.reviewComments" class="w-50 m-2" placeholder="请输入" />
				</div>
			</div>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="auditCenleClick">取消</el-button>
					<el-button type="primary" @click="auditSubimitClick"> 保存 </el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 批量审核 -->
		<el-dialog @close="approvalRegistrationInfoIdListClose" v-model="approvalRegistrationInfoIdListShow" width="30%">
			<template #header>
				<h3>是否授予比赛资格?</h3>
			</template>
			<div class="menberInfo">
				<div class="radioBox">
					<div class="radioText"><span>*</span>报名审核</div>
					<el-radio-group v-model="approvalRegistrationInfoIdList.registrationStatus">
						<el-radio :label="1">授予比赛资格</el-radio>
						<el-radio :label="0">不授予比赛资格</el-radio>
					</el-radio-group>
				</div>
				<div class="text">
					<span>审核备注：</span>
					<el-input
						type="textarea"
						v-model="approvalRegistrationInfoIdList.reviewComments"
						class="w-50 m-2"
						placeholder="请输入"
					/>
				</div>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="approvalRegistrationInfoIdListClose">取消</el-button>
					<el-button type="primary" @click="approvalRegistrationInfoIdListSubmit"> 确认 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="tsx" setup name="registration">
import { ElMessage, ElNotification } from "element-plus";
import type { FormRules, FormInstance } from "element-plus";
import { Download, Files, CirclePlus } from "@element-plus/icons-vue";
import { ref, reactive, watch } from "vue";
import registarationApi from "@/api/modules/registarationinfo";
import achievementApi from "@/api/modules/competitionAchievement";
import api from "@/api/modules/paymentOrderInfo";
import competitionProjectApi from "@/api/modules/competitionProject";
// import employee from "@/api/modules/employee";
import competition from "@/api/modules/competition";
import { dateFormat } from "@/utils/util";
import * as XLSX from "xlsx";
import { ColumnProps } from "@/components/ProTable/interface";
// import { GlobalStore } from "@/stores";
import proTable from "@/components/ProTable/index.vue";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref();
// const { isPlatform } = GlobalStore();
const centerDialogVisible = ref<boolean>(false); //添加报名或者编辑报名
const AuditModel = ref<boolean>(false); //审核报名
const AuditForm = ref({
	id: "",
	competeName: "",
	competeIdNo: "",
	competitionName: "",
	competitionProjectName: "",
	competitionStartTime: "",
	competitionEndTime: "",
	maxEmployeeNum: 0,
	sensorsMaxNum: 0,
	remainingSeats: 0,
	registrationNo: 0,
	projectDateTImeStr: ""
});
const gameType = ref<number>(2); //添加报名和编辑报名是否为团队赛
const ruleFormRef = ref<FormInstance>();
// 表格
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	Order: "",
	Sort: ""
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 datalist && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
	if (data.data == null) {
		data.data = [];
	}
	return {
		list: data.data,
		total: data.totalCount
	};
};
// 赛事选项
const getCompetitionsList = async () => {
	let { result } = await api.GetCompetitionsList();
	let { data, code } = result as any;
	if (code != 200) {
		return [];
	}
	data.unshift({ name: "全部", id: "" });
	return result;
};
const headerRender = (row: ColumnProps) => {
	return (
		<el-tooltip class="box-item" effect="dark" content={row.label} placement="top-start">
			{row.label}
		</el-tooltip>
	);
};
// 比赛项目下啦列表
const project = ref<Array<any>>([]);
// 监听赛事选择
watch(
	() => proTableRef.value?.searchParam.competition,
	async () => {
		if (!proTableRef.value?.searchParam.competition) return;
		proTableRef.value.searchParam.project = "";
		let { result } = await achievementApi.GetCompetionProjectListByCompetionIdApi(proTableRef.value?.searchParam.competition);
		if (result.code != 200) return;
		project.value.length = 0;
		project.value.push(...[{ name: "全部", id: "" }, ...result.data]);
	}
);
// 表格数据变化，清空批量选项
watch(
	() => proTableRef.value?.tableData,
	() => {
		proTableRef.value.clearSelection();
	}
);
//批量审核
const selectable = (row: any) => {
	return row.registrationStatus === "待审核";
};
// 搜索菜单结束时间一定要大于开始时间
const gameDisablesDate = (time: any) => {
	let startTime = proTableRef.value?.searchParam.startTime;
	if (!startTime) {
		return false;
	}
	const _minTime = new Date(startTime).getTime();
	return time.getTime() < _minTime;
};
const signDisablesDate = (time: any) => {
	let startRegistrationSubmissionTime = proTableRef.value?.searchParam.startRegistrationSubmissionTime;
	if (!startRegistrationSubmissionTime) {
		return false;
	}
	const _minTime = new Date(startRegistrationSubmissionTime).getTime();
	return time.getTime() < _minTime;
};
// 搜索菜单开始时间一定小雨开始时间
const gameStartDisablesDate = (time: any) => {
	let endTime = proTableRef.value?.searchParam.endTime;
	if (!endTime) {
		return false;
	}
	const _minTime = new Date(endTime).getTime();
	return time.getTime() > _minTime;
};
const signStartDisablesDate = (time: any) => {
	let endRegistrationSubmissionTime = proTableRef.value?.searchParam.endRegistrationSubmissionTime;
	if (!endRegistrationSubmissionTime) {
		return false;
	}
	const _minTime = new Date(endRegistrationSubmissionTime).getTime();
	return time.getTime() > _minTime;
};
// 表格配置项
const columns = ref<Partial<ColumnProps>[]>([
	{ type: "selection", width: 60, selectable, fixed: "left" },
	{ prop: "competeName", headerRender, label: "参赛人" },
	{ prop: "competeTel", headerRender, label: "联系电话" },
	// { prop: "teamName", headerRender, label: "所属团队" },
	{ prop: "competeIdNo", headerRender, label: "身份证" },
	{ prop: "sensorNumber", headerRender, label: "感应器" },
	{
		prop: "competeTeamName",
		headerRender,
		label: "参赛队名"
		// render: scope => {
		// 	return <>{scope.row.competeTeamName || "--"}</>;
		// }
	},
	{ prop: "competitionName", headerRender, label: "赛事名称" },
	{ prop: "competitionProjectName", headerRender, label: "参赛项目" },
	// { prop: "competitionStartTimeStr", headerRender, label: "比赛时间" },
	// { prop: "competitionAddress", headerRender, label: "比赛地点" },
	// {
	// 	prop: "merchant",
	// 	label: "赛事所属商户",
	// 	isShow: !isPlatform,
	// 	headerRender,
	// 	render: (scope: { row: any }) => {
	// 		return <> {scope.row.merchant || "无"} </>;
	// 	}
	// },
	{ prop: "registrationSubmissionTimeStr", headerRender, label: "报名提交时间" },
	// {
	// 	prop: "employeeName",
	// 	headerRender,
	// 	label: "提交用户",
	// 	render: scope => {
	// 		return <>{scope.row.employeeName || "--"}</>;
	// 	}
	// },
	// {
	// 	prop: "employeeTelephone",
	// 	headerRender,
	// 	label: "提交用户联系电话",
	// 	render: scope => {
	// 		return <>{scope.row.employeeTelephone || "--"}</>;
	// 	}
	// },
	{ prop: "paymentOrderNo", headerRender, label: "关联订单号" },
	{ prop: "registrationSource", headerRender, label: "报名来源" },
	{
		prop: "registrationStatus",
		label: "状态",
		headerRender,
		enum: [
			{
				label: "全部",
				value: 0
			},
			{
				label: "待审核",
				value: 1
			},
			{
				label: "报名成功",
				value: 2
			},
			{
				label: "报名失败",
				value: 3
			}
		],
		search: { el: "select" },
		render: scope => {
			return <>{scope.row.registrationStatus}</>;
		}
	},
	{
		prop: "reviewComments",
		headerRender,
		label: "审核备注"
		// render: scope => {
		// 	return <>{scope.row.reviewComments || "--"}</>;
		// }
	},
	{
		prop: "auditTime",
		headerRender,
		label: "审核时间",
		render: scope => {
			return <>{scope.row.auditTime || ""}</>;
		}
	},
	{
		prop: "reviewedUser",
		headerRender,
		label: "审核人"
		// render: scope => {
		// 	return <>{scope.row.reviewedUser || "--"}</>;
		// }
	},
	{
		prop: "competition",
		label: "赛事名称",
		isShow: false,
		enum: getCompetitionsList,
		search: {
			el: "select-v2",
			props: {
				filterable: true,
				onchange: (val: any) => {
					console.log(val);
				}
			}
		},
		fieldNames: { label: "name", value: "id" }
	},
	{
		prop: "project",
		label: "比赛项目",
		isShow: false,
		enum: project.value,
		search: { el: "select", props: { filterable: true } },
		fieldNames: { label: "name", value: "id" }
	},
	{
		prop: "startTime",
		label: "比赛开始时间",
		isShow: false,
		search: { el: "date-picker", props: { type: "date", ["value-format"]: "YYYY-MM-DD", disabledDate: gameStartDisablesDate } }
	},
	{
		prop: "endTime",
		label: "比赛结束时间",
		isShow: false,
		search: { el: "date-picker", props: { type: "date", ["value-format"]: "YYYY-MM-DD", disabledDate: gameDisablesDate } }
	},
	{
		prop: "startRegistrationSubmissionTime",
		label: "报名提交开始时间",
		isShow: false,
		search: { el: "date-picker", props: { type: "date", ["value-format"]: "YYYY-MM-DD", disabledDate: signStartDisablesDate } }
	},
	{
		prop: "endRegistrationSubmissionTime",
		label: "报名提交结束时间",
		isShow: false,
		search: { el: "date-picker", props: { type: "date", ["value-format"]: "YYYY-MM-DD", disabledDate: signDisablesDate } }
	},
	{
		prop: "keyWord",
		label: "关键字",
		isShow: false,
		search: { el: "input", props: { placeholder: "请输入赛事名称/用户姓名/比赛项目" } }
	},
	{ prop: "operation", label: "操作", width: 120, fixed: "right" }
]);

// 批量审核
const batchOperation = (ids: any[]) => {
	if (!ids.length) {
		ElMessage.error("请选中后在操作");
		return;
	}
	approvalRegistrationInfoIdList.value.ids = ids;
	approvalRegistrationInfoIdListShow.value = true;
};
//打开所属团队下拉框
// const handleVisibleChange = async (RealName: string, IDNumber: string, index: number) => {
// 	let res = await employee.GetEmployeeTeamListApi({
// 		RealName, //姓名
// 		IDNumber //身份证号
// 	});
// 	let { data } = res.result;
// 	if (!data) {
// 		addRegFrom.value.EmployeeInfos[index].teamList = [
// 			{
// 				teamName: "没有所属团队",
// 				id: "",
// 				disabled: true
// 			}
// 		];
// 		return;
// 	}
// 	addRegFrom.value.EmployeeInfos[index].teamList = data;
// };
const approvalRegistrationInfoIdListShow = ref<boolean>(false); //批量审核模态框
const employeeInfosShow = ref<boolean>(false); //报名表单显示
const approvalRegistrationInfoIdList = ref<any>({
	ids: [], //审核报名ID
	registrationStatus: 1, //报名状态
	reviewComments: "" //报名备注
});
const approvalRegistrationInfoIdListSubmit = async () => {
	await registarationApi.ApprovalRegistrationInfoListApi(approvalRegistrationInfoIdList.value);
	ElNotification({
		title: "提示",
		message: "操作成功",
		type: "success",
		duration: 1000
	});
	approvalRegistrationInfoIdListShow.value = false;
	proTableRef.value.reset();
};
const approvalRegistrationInfoIdListClose = () => {
	approvalRegistrationInfoIdListShow.value = false;
	approvalRegistrationInfoIdList.value.reviewComments = "";
	approvalRegistrationInfoIdList.value.registrationStatus = 1;
};
// const handleIsCheckedChange = (index: number) => {
// 	let bool: boolean = addRegFrom.value.EmployeeInfos[index].isChecked as boolean;
// 	if (bool) {
// 		addRegFrom.value.EmployeeInfos[index].TeamId = "";
// 	}
// };
const handleModel = () => {
	//添加报名
	centerDialogVisible.value = true;
};
// 提交报名
const handleSubmitClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (valid) {
			let data: Application.ApplicationOptions = JSON.parse(JSON.stringify(addRegFrom.value));
			data.EmployeeInfos = data.EmployeeInfos.map((item: Application.Participants): Application.Participants => {
				delete item.isChecked;
				delete item.isTeamShow;
				delete item.teamList;
				return item;
			});
			registarationApi.AddRegistrationInfoApi(data).then((res: any) => {
				let { code, message } = res.result;
				if (code != 200) {
					ElNotification({
						title: "提示",
						message,
						type: "error"
					});
					return false;
				}
				ElNotification({
					title: "提示",
					message: "报名成功！",
					type: "success"
				});
				proTableRef.value.reset();
				centerDialogVisible.value = false;
			});
		} else {
			ElNotification({
				title: "提示",
				message: "请完善报名信息！",
				type: "warning"
			});
		}
	});
};
const handleCancelClick = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	centerDialogVisible.value = false;
	gameType.value = 2;
	employeeInfosShow.value = false;
	restAddRegFrom();
};
//添加报名数据
const addRegFrom = ref<Application.ApplicationOptions>({
	CompetitionId: "", //赛事ID
	CompetitionProjectId: "", //比赛项目ID
	RegistrationSource: 3, //报名来源（1：小程序；2：H5；3：线下报名）
	officialOrBusiness: 0,
	RequestSource: 0,
	EmployeeInfos: [
		{
			CompeteName: "", //参赛人姓名
			CompeteTel: "", //参赛人电话
			TeamId: "", //团队ID
			CompeteIdNo: "", //参赛人身份证号码
			SensorNumber: "", //感应器
			CompeteTeamName: "", //参赛队名
			openId: "",
			isTeamShow: false,
			isChecked: false,
			teamList: []
		}
	]
});
const employeeInfosForm = reactive<FormRules>({
	CompetitionId: [{ required: true, message: "请选择参加赛事", trigger: "change" }],
	CompetitionProjectId: [{ required: true, message: "请选择比赛项目！", trigger: "change" }],
	CompeteName: [{ required: true, message: "请输入姓名!", trigger: "blur" }],
	CompeteTel: [
		{ required: true, message: "请输入参赛人联系电话！", trigger: "blur" },
		{
			pattern: /^(13[0-9]|14[1|4|5|6|7|8|9]|15[0|1|2|3|5|6|7|8|9]|17[2|3|5|6|7|8]|18[0-9]|19[1|8|9])\d{8}$/,
			message: "手机号格式不正确"
		}
	],
	TeamId: [{ required: true, message: "请选择参赛队名!", trigger: "blur" }],
	CompeteIdNo: [
		{ required: true, message: "请输入参赛人员身份证号！", trigger: "blur" },
		{
			pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X)$)/,
			message: "证件号码格式有误！",
			trigger: "blur"
		}
	],
	SensorNumber: [{ required: true, message: "请输入参赛的感应器！", trigger: "blur" }],
	CompeteTeamName: [{ required: true, message: "请输入参赛队名！", trigger: "blur" }]
});
const restAddRegFrom = () => {
	addRegFrom.value = {
		CompetitionId: "", //赛事ID
		CompetitionProjectId: "", //比赛项目ID
		RegistrationSource: 3, //报名来源（1：小程序；2：H5；3：线下报名）
		officialOrBusiness: 0,
		RequestSource: 0,
		EmployeeInfos: [
			{
				CompeteName: "", //参赛人姓名
				CompeteTel: "", //参赛人电话
				TeamId: "", //团队ID
				CompeteIdNo: "", //参赛人身份证号码
				SensorNumber: "", //感应器
				CompeteTeamName: "", //参赛队名
				openId: "",
				isChecked: false
			}
		]
	};
};
//添加报名
//新增参赛人
const NewPersonClick = (): void => {
	let person_item: Application.Participants = {
		CompeteName: "", //参赛人姓名
		CompeteTel: "", //参赛人电话
		TeamId: "", //团队ID
		CompeteIdNo: "", //参赛人身份证号码
		SensorNumber: "", //感应器
		CompeteTeamName: "", //参赛队名
		openId: "",
		isChecked: false,
		teamList: []
	};
	if (addRegFrom.value.officialOrBusiness == 1) {
		person_item = {
			CompeteName: "", //参赛人姓名
			CompeteTel: "", //参赛人电话
			TeamId: "", //团队ID
			CompeteIdNo: "", //参赛人身份证号码
			SensorNumber: "", //感应器
			CompeteTeamName: "", //参赛队名
			openId: "",
			shipType: "",
			batteryType: "",
			remoteControl: "",
			electricalType: "",
			electricBrand: "",
			isTeamShow: false,
			isChecked: false,
			teamList: []
		};
	}

	addRegFrom.value.EmployeeInfos.push(person_item);
};
const DeletePersonClick = (index: number): void => {
	if (addRegFrom.value.EmployeeInfos.length <= 1) {
		ElNotification({
			title: "提示",
			message: "禁止操作",
			type: "success",
			duration: 1000
		});
		return;
	}
	addRegFrom.value.EmployeeInfos.splice(index, 1);
};
const auditFrom = ref({
	//审核数据
	id: "",
	registrationStatus: 1,
	reviewComments: ""
});

const handleAudit = (id: string) => {
	//表格审核按钮
	AuditModel.value = true;
	auditFrom.value.id = id;
	registarationApi.ApprovalGetRegistrationInfoDetailsApi(id).then((res: any) => {
		let { data } = res.result;
		AuditForm.value = data;
	});
};
const auditSubimitClick = () => {
	//提交审核
	registarationApi.ApprovalRegistrationInfoApi(auditFrom.value).then((res: any) => {
		let { message } = res.result;
		ElNotification({
			title: "提示",
			message,
			type: "success",
			duration: 1000
		});
		AuditModel.value = false;
		auditFrom.value = {
			id: "",
			registrationStatus: 1,
			reviewComments: ""
		};
		proTableRef.value.reset();
	});
};
const auditCenleClick = () => {
	//取消审核
	AuditModel.value = false;
	auditFrom.value = {
		id: "",
		registrationStatus: 1,
		reviewComments: ""
	};
};
interface QueryList {
	competitionList: Array<any>;
	projectList: Array<any>;
}
const queryList = reactive<QueryList>({
	competitionList: [],
	projectList: []
});
const getCompetitionListApi = async () => {
	let { result } = await competition.GetNotClosedCompetitionListApi();
	let { data, code } = result as any;
	if (code != 200) {
		return;
	}
	queryList.competitionList = [
		...data.map((item: any) => {
			console.log(item, "item");

			return {
				lable: item.name,
				value: item.id,
				officialOrBusiness: item.officialOrBusiness
			};
		})
	];
};
getCompetitionListApi();
const handleCompetitionChange = (e: any) => {
	addRegFrom.value.officialOrBusiness = queryList.competitionList.find((item: any) => item.value == e).officialOrBusiness;
	employeeInfosShow.value = false;
	addRegFrom.value.CompetitionProjectId = "";
	getProjectApi();
};
const getProjectApi = async () => {
	let ret = await competitionProjectApi.GetComProjectListByComIdApi(addRegFrom.value.CompetitionId);
	let { code, data } = ret.result;
	if (code !== 200) {
		queryList.projectList = [];
		ElNotification({
			title: "提示",
			message: "此赛事暂无项目，请选择其他赛事报名！",
			type: "warning"
		});
		return;
	}
	queryList.projectList = [
		...data.map((item: any) => {
			return {
				lable: item.name,
				value: item.id
			};
		})
	];
};
const handleProjectTypeChange = async (id: string) => {
	employeeInfosShow.value = false;
	let { result } = await competitionProjectApi.GetCompetitionPorjectDetailsByIdApi(id);
	gameType.value = result.data.gameType;
	let res = await competitionProjectApi.GetMaxEmployeeNumApi(id);
	let { isFull, maxEmployeeNum } = res.result.data;
	if (isFull && maxEmployeeNum !== 0) {
		ElNotification({
			title: "提示",
			message: `很抱歉，此项目已经达到最大报名人数${maxEmployeeNum}人！`,
			type: "error"
		});
		return;
	}
	if (addRegFrom.value.officialOrBusiness == 1) {
		addRegFrom.value.EmployeeInfos = [
			{
				CompeteName: "", //参赛人姓名
				CompeteTel: "", //参赛人电话
				TeamId: "", //团队ID
				CompeteIdNo: "", //参赛人身份证号码
				SensorNumber: "", //感应器
				CompeteTeamName: "", //参赛队名
				openId: "",
				shipType: "",
				batteryType: "",
				remoteControl: "",
				electricalType: "",
				electricBrand: "",
				isTeamShow: false,
				isChecked: false,
				teamList: []
			}
		];
	} else {
		addRegFrom.value.EmployeeInfos = [
			{
				CompeteName: "", //参赛人姓名
				CompeteTel: "", //参赛人电话
				TeamId: "", //团队ID
				CompeteIdNo: "", //参赛人身份证号码
				SensorNumber: "", //感应器
				CompeteTeamName: "", //参赛队名
				openId: "",
				isTeamShow: false,
				isChecked: false,
				teamList: []
			}
		];
	}

	employeeInfosShow.value = true;
};
// 调整数据顺序
const reorderJSON = (obj: any) => {
	const keyOrder = [
		"id",
		"competeName",
		"competeTel",
		"competeIdNo",
		"sensorNumber",
		"competeTeamName",
		"competitionName",
		"competitionProjectName",
		// "competitionStartTimeStr",
		// "competitionEndTime",
		// "competitionAddress",
		// "merchant",
		"registrationSubmissionTimeStr",
		"employeeId",
		// "employeeName",
		// "employeeTelephone",
		"paymentOrderNo",
		"registrationSource",
		"registrationStatus",
		"reviewComments",
		"auditTime",
		"reviewedUserId",
		"reviewedUser"
	];

	return Object.keys(obj)
		.sort((a, b) => keyOrder.indexOf(a) - keyOrder.indexOf(b))
		.reduce(
			(result, key) => ({
				...result,
				[key]: obj[key]
			}),
			{}
		);
};
//检测用户输入完姓名和身份证
const handleIsTeamShowBlur = (index: number) => {
	let reg =
		/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;
	let { CompeteIdNo, CompeteName } = addRegFrom.value.EmployeeInfos[index];
	if (!CompeteName || !reg.test(CompeteIdNo)) {
		addRegFrom.value.EmployeeInfos[index].isTeamShow = false;
		return;
	}
	addRegFrom.value.EmployeeInfos[index].isTeamShow = true;
};
const DowloadExcelClick = () => {
	const data = JSON.parse(JSON.stringify(proTableRef.value?.tableData)).map((i: any) => {
		i = reorderJSON(i);
		return i;
	});
	let head: any = {};
	columns.value.forEach(i => {
		if (!i.isShow) return;
		if (i.prop == "operation") return;
		if (i.type == "selection") return;
		head[i.prop!] = i.label!;
	});
	const values = data.map((item: any) => {
		const obj: any = {};
		for (const k in item) {
			if (head[k]) {
				obj[head[k]] = item[k];
			}
		}
		return obj;
	});
	const worksheet = XLSX.utils.json_to_sheet(values);
	const workbook = XLSX.utils.book_new();
	XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
	const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
	const blob = new Blob([excelBuffer], { type: "application/octet-stream" });
	const url = URL.createObjectURL(blob);
	const link = document.createElement("a");
	link.href = url;
	link.setAttribute("download", "报名列表.xlsx");
	document.body.appendChild(link);
	link.click();
	document.body.removeChild(link);
};
</script>

<style lang="scss" scoped>
::v-deep.el-descriptions {
	padding: 15px;
	background: #d8d8d8;
	.el-descriptions__body {
		background: #d8d8d8 !important;
	}
}
.menberInfo {
	padding: 15px;
	.name {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
		h3 {
			margin-right: 15px;
		}
	}
	.raceOption {
		display: flex;
		align-items: center;
		.optionName {
			margin-right: 15px;
		}
	}
	.count {
		display: flex;
		align-items: center;
		margin: 10px 0;
		.personMax {
			margin-right: 10px;
		}
	}
}
.radioBox {
	display: flex;
	align-items: center;
	margin: 20px 0;
	.radioText {
		margin-right: 10px;
		span {
			color: red;
		}
	}
	.radioinput {
		margin-right: 10px;
	}
}
.text {
	display: flex;
	align-items: center;
	span {
		width: 100px;
	}
}
.person_item {
	padding: 15px;
	margin-bottom: 15px;
	background: #f0f0f0;
	.person_item_btn {
		display: flex;
		justify-content: flex-end;
		width: 150px;
	}
}
.header-button-lf {
	float: none !important;
	width: 100%;
	.header-btn-box {
		display: flex;
		flex: 1;
		align-items: center;
		justify-content: space-between;
		width: 100%;
	}
}
</style>
